package cn.harry.modular.cp.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.cp.execel.UserImportListener;
import cn.harry.modular.cp.service.EvaluationUserService;
import cn.harry.modular.cp.domain.EvaluationUser;
import cn.harry.modular.cp.vo.EvaluationUserLoginCodeVO;
import cn.harry.modular.cp.vo.EvaluationUserVO;
import cn.harry.modular.system.domain.SysUser;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 评测前端控制层
 *
 * @author harry
 * @公众号 Harry技术
 */
@Tag(name = "评测用户接口")
@RestController
@RequestMapping("/evaluationUser")
@RequiredArgsConstructor
public class EvaluationUserController {

    private final EvaluationUserService evaluationUserService;

    /**
     * 分页查询列表
     */
    @Operation(summary = "分页查询")
    @GetMapping(value = "/page")
    public R<IPage<EvaluationUser>> page(@ParameterObject Page<EvaluationUser> page, @ParameterObject EvaluationUser entity) {
        return R.success(evaluationUserService.page(page, Wrappers.lambdaQuery(entity)));
    }

    /**
     * 根据id获取详情
     */
    @Operation(summary = "根据id获取详情")
    @GetMapping(value = "/{id}")
    public R<EvaluationUser> getById(@PathVariable Long id) {
        return R.success(evaluationUserService.getById(id));
    }

    /**
     * 新增
     */
    @Operation(summary = "新增")
    @SysLog(title = "evaluation_user", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Integer> save(@RequestBody EvaluationUser entity) {
        return evaluationUserService.save(entity) ? R.success() : R.failed();
    }

    /**
     * 更新
     */
    @Operation(summary = "更新")
    @SysLog(title = "evaluation_user", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Integer> update(@RequestBody EvaluationUser entity) {
        return evaluationUserService.updateById(entity) ? R.success() : R.failed();
    }

    /**
     * 删除
     */
    @Operation(summary = "删除")
    @SysLog(title = "evaluation_user", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        return evaluationUserService.removeBatchByIds(Arrays.asList(ids)) ? R.success() : R.failed();
    }


    // 导入被测评对象，并回显
    @Operation(summary = "测评对象模板")
    @SysLog(title = "测评对象模板", businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        EasyExcel.write(response.getOutputStream(), EvaluationUserVO.class).sheet("测评对象模板")
                .doWrite(ArrayList::new);
    }


    @Operation(summary = "测评对象导入")
    @PostMapping("import")
    public R importUser(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            throw new RuntimeException("请上传文件!");
        }
        if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
            throw new RuntimeException("请上传正确的excel文件!");
        }
        InputStream inputStream;
        try {
            UserImportListener importListener = new UserImportListener(evaluationUserService);
            inputStream = new BufferedInputStream(file.getInputStream());
            ExcelReaderBuilder builder = EasyExcel.read(inputStream, EvaluationUserVO.class, importListener);
            builder.doReadAll();
            //返回读取的内容
            return R.success(importListener.getList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success("操作成功");
    }

    // 现在导入，保存测评对象
    @Operation(summary = "现在导入，保存测评对象")
    @PostMapping("importSave/{evaluationId}")
    public R importSave(@PathVariable Long evaluationId,@RequestBody List<EvaluationUser> list) {
        return evaluationUserService.importSave(evaluationId,list) ? R.success() : R.failed();
    }

    // 获取登录码
    @Operation(summary = "获取登录码")
    @GetMapping("/getLoginCode/{evaluationId}")
    public R<List<EvaluationUserLoginCodeVO>> getLoginCode(@PathVariable Long evaluationId) {
        return R.success(evaluationUserService.getLoginCode(evaluationId));
    }

    // 导出登录码
    @Operation(summary = "导出登录码")
    @GetMapping("/exportLoginCode/{evaluationId}")
    public void exportLoginCode(@PathVariable Long evaluationId, HttpServletResponse response) throws IOException {
        List<EvaluationUserLoginCodeVO> list = evaluationUserService.getLoginCode(evaluationId);
        EasyExcel.write(response.getOutputStream(), EvaluationUserLoginCodeVO.class).sheet("登录码")
                .doWrite(list);
    }

    // 根据登录码 获取评测对象
    @Operation(summary = "根据登录码 获取评测对象")
    @GetMapping("/getUserByLoginCode/{loginCode}")
    public R<EvaluationUser> getUserByLoginCode(@PathVariable String loginCode) {
        return R.success(evaluationUserService.getUserByLoginCode(loginCode));
    }

}
